<template>
  <el-dialog :title="titleName" custom-class="menu-dialog" width="580px"
             :visible.sync="visible"
             center
             :before-close="modelClose" 
             @open="modelOpen" 
             :close-on-click-modal="false">
    <el-form :rules="roleHandleRules" 
              ref="menuHandleForm" 
              :model="modelData" 
              :disabled="formDisabled" 
              v-loading="loading">
      <el-row v-if="modelType === 'subAdd'">
        <el-col :span="24">
          <el-form-item label="上级菜单" :label-width="formLabelWidth">
            <el-input :value="modelData.parentTxt" :disabled="modelType !== 'add'"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="modelType === 'add'" :span="24" >
        <el-col :span="24">
          <el-form-item label="类型编码" :label-width="formLabelWidth" prop="type" >
            <el-input v-model.trim="modelData.type" maxlength="10" autocomplete="off" placeholder="请输入整形编码"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="modelType !== 'add' && modelData.category != 0" :span="24" >
        <el-col :span="24">
          <el-form-item label="菜单类型" :label-width="formLabelWidth" prop="category">
            <el-select v-model="modelData.category" :disabled="disableMenuCategory" placeholder="请选择菜单类型" style="width: 444px">
              <el-option v-for="item of $enums.MENU_CATEGORY" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="显示次序" :label-width="formLabelWidth" prop="number" >
            <el-input-number v-model.trim="modelData.number" placeholder="请输入显示次序" :min="1" :max="10000" size="small" style="width: 444px"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="菜单图标" :label-width="formLabelWidth" prop="icon" >
            <el-select v-model="modelData.icon" placeholder="请选择菜单图标" style="width: 444px">
              <el-option v-for="item of iconList" :key="item.value" :label="item.label" :value="item.value">
                <div style="display:flex;align-items: center;">
                <div style="display:flex;align-items: center;">
                  <i class="icon iconfont" :class="`icon-`+ item.value"></i>
                </div>
                <div>{{ item.label }}</div>
              </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="菜单名称" :label-width="formLabelWidth" prop="cname" >
            <el-input v-model.trim="modelData.cname" maxlength="50" autocomplete="off" placeholder="请输入菜单名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="路由名称" :label-width="formLabelWidth" prop="rname">
            <el-input v-model.trim="modelData.rname" maxlength="100" autocomplete="off" placeholder="请输入路由名，如：userManager"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="modelType != 'add'">
        <el-col :span="24">
          <el-form-item label="父菜单名" :label-width="formLabelWidth" v-if="modelType !== 'subAdd'">
            <el-input v-if="modelType == 'info'" 
                      v-model.trim="modelData.parentTxt" 
                      autosize 
                      autocomplete="off" 
                      placeholder="请输入父菜单"
                      :disabled="disableMenuCategory" >
            </el-input>
            <el-cascader v-if="modelType == 'add' || modelType == 'edit'" 
                         :disabled="disableMenuCategory" 
                         v-model="selectParent" 
                         :options="treeMenuList" 
                         :props="{ value: 'id', label: 'cname', checkStrictly: true }" 
                         :show-all-levels="false" 
                         clearable 
                         style="width: 100%">
            </el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 模块名称 模块描述 父菜单名称  -->
    </el-form>
    <div slot="footer" v-if="btnVisible">
      <el-button type="primary" @click="formSubmit" :loading="loading">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  name: 'menuMgrHandleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    modelType: {
      type: String,
      required: true,
      default: () => {
        return 'info';
      },
    },
    modelData: {
      type: Object,
      default: () => {
        return {
          app: process.env.VUE_APP_SYSTEM_NAME,
          cname: '',
          rname: '',
          pid: '',
          type: 1,
          category: 1,
          icon: 'dingdan',
          number: 1
        };
      },
    },
    allMenuList: {
      type: Array,
      default: () => [],
    },
    treeMenuList: {
      type: Array,
      default: () => [],
    },
    allInterfaceList: {
      type: Array,
      default: () => [],
    },
    treeInterfaceList: {
      type: Array,
      default: () => [],
    }
  },
  data() {
    return {
      titleName: '详情',
      formLabelWidth: '80px',
      dialogFormVisible: false,
      formDisabled: false,
      btnVisible: true,
      loading: false,
      selectParent: [],
      iconList: [{
          label: '消息管理',
          value: 'xiaoxi'
        },{
          label: '系统配置',
          value: 'setting'
        },{
          label: '电脑图标',
          value: 'diannao'
        },{
          label: '手机图标',
          value: 'shouji'
        },{
          label: '密码图标',
          value: 'mima1'
        },{
          label: '问号图标',
          value: 'wenhao'
        },{
          label: '验证码',
          value: 'yanzhengma'
        },{
          label: '收缩图标',
          value: 'shrink-s'
        },{
          label: '调色盘',
          value: 'zhuti_tiaosepan'
        },{
          label: '菜单列表',
          value: 'caidan'
        },{
          label: '用户列表',
          value: 'user'
        },{
          label: '密码管理',
          value: 'mima'
        },{
          label: '更多列表',
          value: 'more'
        },{
          label: '货物管理',
          value: 'huowu'
        },{
          label: '货主管理',
          value: 'huozhuguanli'
        },{
          label: '事项登记',
          value: 'shixiangdengji'
        },{
          label: '报建登记',
          value: 'guanxianbaojiandengji'
        },{
          label: '数据登记',
          value: 'dengji'
        },{
          label: '子账号管理',
          value: 'zizhanghaoguanli'
        },{
          label: '物流管理',
          value: 'wuliu'
        },{
          label: '账号管理',
          value: 'zhanghaoguanli'
        },{
          label: '站点接入',
          value: 'zhandianjieru'
        },{
          label: '视频管理',
          value: 'shipin'
        },{
          label: '爱心服务',
          value: 'aixin'
        },{
          label: '优惠券管理',
          value: 'youhuiquan'
        },{
          label: '消息中心',
          value: 'xiaoxizhongxin'
        },{
          label: '电话符号',
          value: '31dianhua'
        },{
          label: '订单管理',
          value: 'dingdan'
        },{
          label: '地址管理',
          value: 'dizhiguanli'
        },{
          label: '拆箱入库',
          value: 'warehouse'
        },{
          label: '物流快递',
          value: 'wuliukuaidi'
        },{
          label: '快递服务',
          value: 'jikuaidi'
        },{
          label: '二维码管理',
          value: 'icon2'
        },{
          label: '皇冠图标',
          value: 'huangguan'
        },{
          label: '身份管理',
          value: 'ID-card'
        },{
          label: '首页',
          value: 'home'
        },{
          label: '我的',
          value: 'wode'
        },{
          label: '市场分析',
          value: 'shichangfenxi'
        },{
          label: '商品管理',
          value: 'shangpinguanli'
        },{
          label: '用户管理',
          value: 'yonghuguanli'
        },{
          label: '系统管理',
          value: 'xitongguanli'
        },{
          label: '事件信息',
          value: 'shijian-011'
        },{
          label: '实时交易',
          value: 'shishijiaoyishuju-01'
        },{
          label: '警告分析',
          value: 'hangweifenxijinggao-01'
        }
      ],
      disableMenuCategory: false,
      selectInterfaces: [], // 选择关联的接口
      parentTxt: '',        // 查看详情状态下，显示父菜单的名称
      interfacesTxt: '',    // 查看详情状态下，显示关联接口的名称
      validRoute: false,
      rules1: {
        app: this.$Validate.otherTxt(true, '请输入所属应用'),
        type: this.$Validate.integer(true, '请输入菜单类型编码'),
        cname: this.$Validate.otherTxt(true, '请输入菜单名称'),
      },
      rules2: {
        app: this.$Validate.otherTxt(true, '请输入所属应用'),
        type: this.$Validate.integer(true, '请输入菜单类型编码'),
        cname: this.$Validate.otherTxt(true, '请输入菜单名称'),
        rname: [{required: true, message: '只能输入英文', trigger: 'blur'}]
      },
    }
  },
  computed: {
    roleHandleRules(){
      if(this.validRoute){
        return this.rules2;
      }
      return this.rules1;
    }
  },
  methods: {
    // 解决el-input莫名无法输入的问题
    change() {
      this.$forceUpdate();
    },
    // 对话框打开
    modelOpen() {
      switch (this.modelType) {
        case 'add':
          this.modelTypeChange('添加菜单', false, true);
          this.selectParent = [];
          this.validRoute = false;
          break;
        case 'info':
          this.modelTypeChange('菜单详情', true, false);
          break;
        case 'edit':
          this.modelTypeChange('编辑菜单', false, true);
          this.initParent();
          // 系统根菜单
          if(this.modelData.category == 0){
            this.disableMenuCategory = true;
          }
          this.validRoute = (this.modelData.category != 0);
          break;
        case 'subAdd':
          this.modelData.pid = this.modelData.id;
          this.modelData.subParentTxt = this.modelData.cname;
          this.modelData.cname = '';
          this.modelData.rname = '';
          this.modelTypeChange('添加子菜单', false, true);
          this.selectParent = [];
          this.validRoute = true;
          // 系统根菜单
          if(this.modelData.category == 0){
            this.modelData.category = 1;
            this.disableMenuCategory = true;
          }
          break;
        default:
          break;
      }
    },
    // 模式切换
    modelTypeChange(titleName, formDisabled, btnVisible) {
      this.titleName = titleName;
      this.formDisabled = formDisabled;
      this.btnVisible = btnVisible;
    },
    // 处理父菜单数据
    initParent() {
      if (this.modelData.pid == undefined || this.modelData.pid == null) {
        this.selectParent = [];
      } else {
        var arr = [], _this = this;
        function findParent(pid) {
          _this.allMenuList.forEach(element => {
            if (element.id == pid) {
              arr.unshift(element.id)
              if (element.pid) {
                findParent(element.pid);
              }
            }
          });
        }
        findParent(this.modelData.pid);
        this.selectParent = arr;
      }
    },
    // 提交表单
    formSubmit() {
      // 最后一个父菜单作为其父亲
      if (this.selectParent.length > 0) {
        this.modelData.pid = this.selectParent[this.selectParent.length - 1];
      }
      // 参数校验
      this.$refs.menuHandleForm.validate((valid) => {
        if (valid) {
          switch (this.modelType) {
            // 添加菜单
            case 'add':
              this.handleAdd(this.modelData);
              break;
            // 编辑菜单
            case 'edit':
              this.handleEdit(this.modelData);
              break;
            // 添加子菜单
            case 'subAdd':
              let subAddData = JSON.parse(JSON.stringify(this.modelData));
              this.$delete(subAddData, 'id')
              this.handleAdd(subAddData);
              break;
            default:
              break;
          }
        }
      });
    },
    // 新增
    handleAdd(formData) {
      this.loading = true;
      this.$api.menu
        .addMenu(formData)
        .then((res) => {
          this.$message.success('菜单添加成功');
          this.loading = false;
          this.modelClose();
          this.$emit('loadAllList');
          this.$emit('loadList');
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 编辑
    handleEdit(formData) {
      // 父菜单不能为自己
      if (formData.id === formData.pid) {
        return this.$message.error('不能把父菜单编辑为自身');
      }
      // 父菜单不能为子菜单
      if (this.findChildrenName(formData)) {
        return this.$message.error('不能把父菜单作为自身子菜单');
      }
      // 更新菜单
      this.loading = true;
      this.$api.menu
        .updateMenu(formData)
        .then((res) => {
          this.$message.success('菜单更新成功');
          this.loading = false;
          this.modelClose();
          this.$emit('loadAllList');
          this.$emit('loadList');
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 重置表单
    resetForm() {
      this.$nextTick(() => {
        this.$refs.menuHandleForm.resetFields();
      });
    },
    // 对话框关闭
    modelClose() {
      // 恢复启用
      this.disableMenuCategory = false;
      // 重置表单
      this.resetForm();
      // 直接修改父组件的属性
      this.$emit('update:visible', false); 
    },
    // 检查父菜单是否作为子菜单
    findChildrenName(ele) {
      let flag = false;
      // 递归找子菜单
      function find(item) {
        if (item.id === ele.pid) {
          flag = true;
        }
        if (item.children) {
          item.children.forEach(element => {
            find(element);
          })
        }
      }
      find(ele);
      return flag;
    },
  },
}
</script>

<style lang="scss" scope>
.menu-dialog {
  .el-dialog__body {
    max-height: 50vh;
  }
  .custom-height {
    .el-input__inner {
      height: 32px !important;
    }
  }
}
</style>